﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace Mls.IO
{
    public class IncorrectFileFormatException : Exception
    {
        public IncorrectFileFormatException()
            : base("Mls file header is in incorrect format")
        {
        }
    }

    public class DocumentHeader
    {
        private const int HeaderSize = 0x28;
        private const int HeaderNextPrevSize = 12;

        private const int IdentifierOffset = 0;
        private const int IdentifierLength = 3;
        private const int VersionOffset = 4;
        private const int VersionLength = 4;
        private const int LanguagesStart = 0x16;
        private const int LanguagesEnd = 0x26;
        private const int LanguagesStep = 3;
        private const int SkippedHeaderData = 0x150;

        private const int MaxSupportedLanguages = 5;

        public bool[] IsLangSupported = new bool[MaxSupportedLanguages];
        public string Version { get; private set; }
        public string PreviousDocument { get; private set; }
        public string NextDocument { get; private set; }

        private DocumentHeader(BinaryReader reader)
        {
            byte[] header = reader.ReadBytes(HeaderSize);

            if (header.Length != HeaderSize)
                throw new IncorrectFileFormatException();

            if (ASCIIEncoding.ASCII.GetString(header, IdentifierOffset, IdentifierLength) != "MLS")
                throw new IncorrectFileFormatException();

            Version = ASCIIEncoding.ASCII.GetString(header, VersionOffset, VersionLength);

            for (int i = 0; i < IsLangSupported.Length; i++)
                IsLangSupported[i] = false;

            for (int i = LanguagesStart; i < LanguagesEnd; i += LanguagesStep)
                if (header[i] >= 0x30 && header[i] < 0x36)
                    IsLangSupported[header[i] - 0x30] = true;

            PreviousDocument = ASCIIEncoding.ASCII.GetString(reader.ReadBytes(HeaderNextPrevSize)).TrimEnd(new char[] { ' ', '\0' });
            NextDocument = ASCIIEncoding.ASCII.GetString(reader.ReadBytes(HeaderNextPrevSize)).TrimEnd(new char[] { ' ', '\0' });

            if (reader.ReadBytes(SkippedHeaderData).Length != SkippedHeaderData)
                throw new IncorrectFileFormatException();
        }

        public static DocumentHeader Read(BinaryReader reader)
        {
            return new DocumentHeader(reader);
        }
    }
}
